<template>
  <ScrollContainer class="pr-4" v-loading="loading" :loading-tip="t('common.loadingText')">
    <div>
      <div class="flex items-center mb-2">
        <div class="mr-2 w-46px">数据源:</div>
        <div
          ><Select
            :options="formDataOptions"
            style="width: 145px"
            placeholder="请选择"
            v-model:value="currentCode"
            @change="handleChangeForm"
        /></div>
      </div>
      <div class="flex items-center mb-2">
        <div class="mr-2 w-46px">表名:</div>
        <div>
          <Select
            :options="tableDataSource"
            style="width: 145px"
            placeholder="请选择"
            v-model:value="currentTableCode"
            @change="handleChangeTables"
          />
        </div>
      </div>
      <div class="flex items-center mb-2">
        <div class="mr-2 w-46px">SQL:</div>
        <div class="flex">
          <div class="mr-2 cursor-pointer" @click="handleBtn('sqlLoad')">选择</div>
          <div class="mr-2 cursor-pointer" @click="handleBtn('sqlInsert')">增加</div>
          <div class="mr-2 cursor-pointer" @click="handleBtn('sqlDelete')">删除</div>
          <div class="mr-2 cursor-pointer" @click="handleBtn('sqlUpdate')">修改</div>
        </div>
      </div>
      <Divider :dashed="true">字段</Divider>
    </div>
    <ScrollContainer>
      <div class="h-43vh">
        <div
          v-for="item in fieldsDataOptions"
          :key="item.value"
          class="cursor-pointer hover:underline"
          @click="handleFieldsItem(item)"
        >
          {{ item.value }}
        </div>
      </div>
    </ScrollContainer>
  </ScrollContainer>
</template>

<script lang="ts" setup>
  import { ref, unref, onMounted, reactive } from 'vue';
  import { ScrollContainer } from '/@/components/Container';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Select, Divider } from 'ant-design-vue';
  import {
    getIdeGetDbSources,
    getIdeGetTables,
    getIdeGetTableFields,
    getIdeGetSqlsByDb,
  } from '/@/api/flowManage/flowManage';
  import { isArray } from '/@/utils/is';
  const { t } = useI18n();
  const props = defineProps({
    formCode: {
      type: String,
      default: '',
    },
  });
  interface FormDataOptions {
    code: string;
    name: string;
    label?: string;
    value?: string;
  }
  const emits = defineEmits(['selField']);
  const loading = ref(false);
  const formDataOptions = ref<FormDataOptions[]>([]);
  const fieldsDataOptions = ref([]);
  const currentCode = ref('');

  // const handleResetFields = () => {
  //   resetFields();
  // };
  //获取表单
  function fetch() {
    formDataOptions.value = [];
    loading.value = true;
    getIdeGetDbSources()
      .then((res) => {
        formDataOptions.value = res || [];
        if (isArray(formDataOptions.value) && formDataOptions.value.length) {
          formDataOptions.value.forEach((item: FormDataOptions) => {
            item.label = item.name;
            item.value = item.name;
          });
          currentCode.value = formDataOptions.value[0].name;
          getTablesData();
        }
      })
      .finally(() => {
        loading.value = false;
      });
  }
  //数据源change
  const handleChangeForm = () => {
    getTablesData();
  };

  //获取表名
  const tableDataSource = ref<any>([]);
  const currentTableCode = ref('');
  const getTablesData = async () => {
    try {
      tableDataSource.value = [];
      currentTableCode.value = '';
      if (!unref(currentCode)) return;
      loading.value = true;
      const res = await getIdeGetTables({ dbSource: unref(currentCode) });
      loading.value = false;
      if (isArray(res)) {
        res.forEach((item) => {
          tableDataSource.value.push({
            label: item,
            value: item,
          });
        });
        currentTableCode.value = tableDataSource.value[0].value;
        handleChangeTables();
      }
    } catch (err) {
      console.log('getTablesDta', err);
      loading.value = false;
    }
  };
  //表名change
  const handleChangeTables = () => {
    getFieldsData();
    getIdeGetSqlsByDbData();
  };

  //初始化
  onMounted(() => {
    fetch();
  });
  //获取表对应字段
  const getFieldsData = async () => {
    try {
      const params = {
        dbSource: unref(currentCode),
        table: unref(currentTableCode),
      };
      loading.value = true;
      fieldsDataOptions.value = [];
      const res = (await getIdeGetTableFields(params)) || [];
      loading.value = false;
      if (isArray(res)) {
        res.forEach((item) => {
          fieldsDataOptions.value.push({
            label: item,
            value: item,
          });
        });
      }
    } catch (err) {
      console.log(err);
      loading.value = false;
    }
  };

  //获取脚本
  let sqlsByFormCode = reactive({});
  const getIdeGetSqlsByDbData = async () => {
    if (!unref(currentCode) && !unref(currentTableCode)) return;

    const params = {
      dbSource: unref(currentCode),
      table: unref(currentTableCode),
    };
    sqlsByFormCode = await getIdeGetSqlsByDb(params);
  };

  //单击字段
  const handleFieldsItem = ({ value }) => {
    emits('selField', value);
  };

  //SQL
  const handleBtn = (type) => {
    emits('selField', sqlsByFormCode[type]);
  };
</script>
